package com.kanche.bigbaby.collection;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kanche.bigbaby.R;
import com.kanche.bigbaby.collection.domain.VehicleDescHighlight;
import com.kanche.bigbaby.collection.domain.VehicleDescIndividual;
import com.kanche.bigbaby.collection.domain.WordChecker;
import com.kanche.bigbaby.collection.view.EvaluateView;
import com.kanche.bigbaby.collection.view.MerchantGridView;
import com.kanche.bigbaby.support.awesome.DrawableAwesome;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.kkche.merchant.awesome.DrawableAwesome;
//import com.kkche.merchant.domain.VehicleDescHighlight;
//import com.kkche.merchant.domain.VehicleDescIndividual;
//import com.kkche.merchant.utils.WordChecker;
//import com.kkche.merchant.view.EvaluateView;
//import com.kkche.merchant.view.MerchantGridView;


public class VehicleDescriptionEditActivity extends BaseActivity implements EvaluateView.OnStarChangListener {
    private EvaluateView[] evaluatestarViews = new EvaluateView[7];
    private int[] evaluatestarId = {R.id.evaluateview_1, R.id.evaluateview_2, R.id.evaluateview_3, R.id.evaluateview_4, R.id.evaluateview_5, R.id.evaluateview_6, R.id.evaluateview_7};
    private String[] starTitle;
    private EditText txt_desc;
    private TextView tv_word_count;
    private StringBuffer sb = new StringBuffer();
    private boolean isUserEdit;
    private WordChecker checker = WordChecker.getInstance();
    private WordChecker.CheckResult result;
    public static final int RESULT_CODE_DESCRIPTION = 301;
    private List<VehicleDescIndividual> individualList;
    private List<VehicleDescHighlight> highlightList;
    private Map<String, String> star_content;
    private String[] star_title_key;
    private List<String[]> arrayStarContent = new ArrayList<String[]>();
    private int[] arrayID = {R.array.star_content_waiguan, R.array.star_content_neishi, R.array.star_content_dongli, R.array.star_content_caokong, R.array.star_content_youhao, R.array.star_content_shushixing, R.array.star_content_kongjian};
    private int tag = 0;
    private String oldDesc;
    private MerchantGridView grid_view_highligh;
    private String[] highlight_array;
    private String[] highlight_key;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vehicle_description_edit);
        toolbar = justFindIt(R.id.toolbar);
        toolbar.setTitle("车辆说明");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        addCheckWord();
        Intent intent = getIntent();
        String content = intent.getStringExtra("content");
        starTitle = getResources().getStringArray(R.array.star_title);
        star_content = new HashMap<String, String>();
        star_title_key = getResources().getStringArray(R.array.star_title_key);
        highlight_array= getResources().getStringArray(R.array.highlight_array);
        highlight_key= getResources().getStringArray(R.array.highlight_key);
        individualList = (List<VehicleDescIndividual>) intent.getSerializableExtra("individualList");
        highlightList = (List<VehicleDescHighlight>)intent.getSerializableExtra("highlightList");
        if(null == individualList || individualList.isEmpty()){
            individualList = new ArrayList<VehicleDescIndividual>();
            for(int i = 0;i < star_title_key.length;i++){
                VehicleDescIndividual individual = new VehicleDescIndividual();
                individual.setName(star_title_key[i]);
                individual.setMark(0);
                individualList.add(i,individual);
            }
        }
        if(null == highlightList || highlightList.isEmpty()){
            highlightList = new ArrayList<VehicleDescHighlight>();
            for(int i = 0;i < highlight_key.length;i++){
                VehicleDescHighlight highlight = new VehicleDescHighlight();
                highlight.setName(highlight_key[i]);
                highlight.setSelected(false);
                highlightList.add(i,highlight);
            }

        }

        for (int i = 0; i < arrayID.length; i++) {
            arrayStarContent.add(getResources().getStringArray(arrayID[i]));
        }
        for (int i = 0; i < evaluatestarViews.length; i++) {
            evaluatestarViews[i] = (EvaluateView) findViewById(evaluatestarId[i]);
            evaluatestarViews[i].setTag(i);
            evaluatestarViews[i].setStarnum(individualList.get(i).getMark());
            star_content.put(star_title_key[i], arrayStarContent.get(i)[individualList.get(i).getMark()]);
            evaluatestarViews[i].setTitle(starTitle[i]);
            evaluatestarViews[i].setOnStarChangListener(this);
        }
        txt_desc = (EditText) findViewById(R.id.txt_desc);
        txt_desc.setText(content);
        tv_word_count = (TextView) findViewById(R.id.tv_word_count);
        grid_view_highligh = (MerchantGridView) findViewById(R.id.grid_view_highligh);
        grid_view_highligh.setAdapter(new GridHighlighAdapter());
        findViewById(R.id.btn_action_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(VehicleDescriptionEditActivity.this)
                        .setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                txt_desc.getText().clear();
                                for (int i = 0; i < evaluatestarViews.length; i++) {
                                    evaluatestarViews[i].setStarnum(0);
                                    individualList.get(i).setMark(0);
                                    star_content.put(star_title_key[i], arrayStarContent.get(i)[individualList.get(i).getMark()]);
                                }
                                isUserEdit = false;
                            }
                        })
                        .setTitle(R.string.msg_dialog_noctice)
                        .setMessage(R.string.msg_clear_content)
                        .create().show();
            }
        });
        txt_desc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_word_count.setText(s.toString().length() + "/300");
            }

            @Override
            public void afterTextChanged(Editable s) {
                oldDesc = txt_desc.getText().toString();
                if (sb.toString().length() < oldDesc.length()) {
                    isUserEdit = true;
                }
            }
        });
        sb.setLength(0);
        for (int i = 0; i < individualList.size(); i++) {
            sb.append(star_content.get(star_title_key[i]));
        }
        if (content.length() > sb.toString().length()) {
            isUserEdit = true;
        }
        tv_word_count.setText(txt_desc.length() + "/300");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_vehicle_step1, menu);
        MenuItem item = menu.findItem(R.id.next);
        item.setIcon(new DrawableAwesome.DrawableAwesomeBuilder(this, R.string.fa_check).build());
        return super.onCreateOptionsMenu(menu);
    }
//
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.next:
                String desc = txt_desc.getEditableText().toString().trim();
                result = checker.check(desc);
                if (!StringUtils.isLengthBetween(desc, 15, 300)) {
                    txt_desc.setError(getString(R.string.error_desc_limit));
                    break;
                }
                String mobileNum = StringUtils.isMobileMode(this,desc);
                if (!TextUtils.isEmpty(mobileNum)) {
                    new AlertDialog.Builder(VehicleDescriptionEditActivity.this)
                            .setTitle("温馨提示")
                            .setCancelable(false)
                            .setMessage("你输入的内容中包含联系方式:" + mobileNum + "请删除后再继续")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                    break;
                }

                if (!result.getOk()) {
                    String stb = new StringBuffer().append("你的描述中含有敏感词\"").append(desc.substring(result.getOffset(), result.getOffset() + result.getLen())).append("\"请返回修改").toString();
                    new AlertDialog.Builder(VehicleDescriptionEditActivity.this)
                            .setTitle("温馨提示")
                            .setCancelable(false)
                            .setMessage(stb)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                    break;
                }

                Intent intent = new Intent();
                intent.putExtra("newcontent", desc);
                intent.putExtra("newindividual", (Serializable) individualList);
                intent.putExtra("newhighlight", (Serializable) highlightList);
                setResult(RESULT_CODE_DESCRIPTION, intent);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void changStra(View view, final int starnum) {
        tag = (Integer) view.getTag();
        if (isUserEdit) {
            new AlertDialog.Builder(VehicleDescriptionEditActivity.this)
                    .setTitle("温馨提示")
                    .setCancelable(false)
                    .setMessage("所选文案会将您之前手动添加的文字全部覆盖，是否确认修改?")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            isUserEdit = false;
                            appendStrToView(starnum);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            evaluatestarViews[tag].setOldStarnum();
                        }
                    })
                    .create().show();
        } else {
            appendStrToView(starnum);
        }
    }

    private void appendStrToView(int starnum) {
        individualList.get(tag).setMark(starnum);
        star_content.put(star_title_key[tag], arrayStarContent.get(tag)[starnum]);
        sb.setLength(0);
        for (int i = 0; i < star_title_key.length; i++) {
            sb.append(star_content.get(star_title_key[i]) == null ? "" : star_content.get(star_title_key[i]));
        }
        txt_desc.setText(sb.toString());
        tv_word_count.setText(txt_desc.length() + "/300");
    }

    private void addCheckWord() {
        try {
            InputStream fis = getResources().getAssets().open("wl.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis,
                    Charset.forName("UTF-8")));
            String word = "";
            while ((word = br.readLine()) != null) {
                checker.addWord(word);
            }
            br.close();
            br = null;
            fis = null;
        } catch (Exception e) {
            System.out.println("read file error " + e.getMessage());
        }
    }

    private class GridHighlighAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return highlightList.size();
        }

        @Override
        public Object getItem(int position) {
            return highlightList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.highligh_view,null);
            }
            final Button bt_highligh = (Button)convertView.findViewById(R.id.bt_highligh);
            final ImageView choose_img = (ImageView)convertView.findViewById(R.id.choose_img);
            bt_highligh.setText(highlight_array[position]);
            if(highlightList.get(position).isSelected()){
                bt_highligh.setTextColor(Color.parseColor("#1bab6c"));
                bt_highligh.setBackgroundColor(Color.parseColor("#d3f3e3"));
                choose_img.setVisibility(View.VISIBLE);
            }else{
                bt_highligh.setTextColor(Color.parseColor("#525459"));
                bt_highligh.setBackgroundColor(Color.parseColor("#ececec"));
                choose_img.setVisibility(View.GONE);
            }
            bt_highligh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(highlightList.get(position).isSelected()){
                        bt_highligh.setTextColor(Color.parseColor("#525459"));
                        bt_highligh.setBackgroundColor(Color.parseColor("#ececec"));
                        choose_img.setVisibility(View.GONE);
                        highlightList.get(position).setSelected(false);
                    }else{
                        bt_highligh.setTextColor(Color.parseColor("#1bab6c"));
                        bt_highligh.setBackgroundColor(Color.parseColor("#d3f3e3"));
                        choose_img.setVisibility(View.VISIBLE);
                        highlightList.get(position).setSelected(true);
                    }
                }
            });
            return convertView;
        }
    }
}
